from flask import Flask, request, jsonify, send_from_directory
import requests
from bs4 import BeautifulSoup
import datetime
import paipan
import hashlib
import json
import os
from datetime import datetime as dt
import logging

app = Flask(__name__)

@app.route('/api/paipan', methods=['POST'])
async def paipan_api():
    data = request.json
    name = data.get('name', '')
    gender = data.get('gender', '')
    birth_date = data.get('birth_date', '')
    birth_time = data.get('birth_time', '')
    location = data.get('location', '')
    
    try:
        # 调用paipan模块中的paipan函数
        sex = int(gender)
        birth_date = datetime.datetime.strptime(birth_date, '%Y-%m-%d').date()
        birth_time = datetime.datetime.strptime(birth_time, '%H:%M').time()
        birth_datetime = datetime.datetime.combine(birth_date, birth_time)
        result = await paipan.crawl_paipan(name, sex, birth_datetime, location)
        
        if result:
            # 检查并创建results目录
            if not os.path.exists('results'):
                os.makedirs('results')
            
            # 生成结果JSON的MD5哈希作为文件名
            result_json = json.dumps(result, ensure_ascii=False)
            md5_hash = hashlib.md5(result_json.encode('utf-8')).hexdigest()
            filename = f"results/{md5_hash}.json"
            
            # 保存结果到JSON文件
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(result_json)
            
            # 记录日志
            log_entry = {
                'timestamp': dt.now().isoformat(),
                'params': data,
                'result_file': filename,
                'success': True
            }
            logging.info(json.dumps(log_entry, ensure_ascii=False))
            
            del result['基本信息']['胎息']
            del result['基本信息']['胎元']
            del result['基本信息']['人元司令分野']
            del result['基本信息']['身宫']
            del result['基本信息']['命宫']
            return jsonify({
                'success': True,
                'data': result
            })
        else:
            return jsonify({
                'success': False,
                'message': '排盘失败'
            })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        })

@app.route('/static/<path:filename>')
def static_files(filename):
    return send_from_directory('static', filename)

# 配置日志
logging.basicConfig(
    filename='paipan.log',
    level=logging.INFO,
    format='%(message)s',
    encoding='utf-8'
)

if __name__ == '__main__':
    app.run(debug=True, port=5000, host='0.0.0.0')  # 允许外部访问 (host='0.0.0.0')，端口为 5000 (port=5000)，调试模式 (debug=True)，使用 HTTPS (ssl_context='adhoc')，使用 HTTP (use_reloader=False)，不使用自动重启 (use_reloade)